﻿using Book_WebAPI.Data;
using Book_WebAPI.Models;

namespace Book_WebAPI.Services
{
    public class AuthorMockRepository : IAuthorRepository
    {
        public void AddAuthor(Author author)
        {
            BookMockData.BookForAuthor.Authors.Add(author);
        }

        public void DeleteAuthor(Author author)
        {
            // 删除作者的同时，也删除他的所有图书
            BookMockData.BookForAuthor.Books.RemoveAll(book => book.authorId == author.id);
            BookMockData.BookForAuthor.Authors.Remove(author);
        }

        public Author GetAuthor(int id)
        {
            var author = BookMockData.BookForAuthor.Authors.FirstOrDefault(author => author.id == id);
            return author;
        }

        public IEnumerable<Author> GetAuthors()
        {
            return BookMockData.BookForAuthor.Authors;
        }

        /// <summary>
        /// 检查该id的作者是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool IsAuthorExists(int id)
        {
            return BookMockData.BookForAuthor.Authors.Any(author => author.id == id);
        }

        public void UpdateAuthor(int id, AuthorUpdate authorUpdate)
        {
            var updateAuthor = GetAuthor(id);

            updateAuthor.id = authorUpdate.id;
            updateAuthor.name = authorUpdate.name;
            updateAuthor.age = authorUpdate.age;
            updateAuthor.email = authorUpdate.email;

            List<Book> needUpdateBook = BookMockData.BookForAuthor.
                Books.Where(book => book.authorId == id).ToList();

            foreach (var book in needUpdateBook) 
            {
                book.authorId = authorUpdate.id;
            }
        }
    }
}
